/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rbh.risk.dao.impl;

import com.rbh.risk.dao.RoleDao;
import com.rbh.risk.entity.Role;
import com.rbh.risk.support.SessionFactorySupport;
import com.rbh.risk.util.Constants;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

@Repository("roleDao")
public class RoleDaoImpl extends SessionFactorySupport implements RoleDao {

    @Override
    public void insert(Role role) throws DataAccessException {
        try {
            super.getSessionFactory().getCurrentSession().save(role);
        } catch (Exception ex) {
            throw ex;
        }
    }

    @Override
    public void update(Role role) throws DataAccessException {
        try {
            super.getSessionFactory().getCurrentSession().update(role);
        } catch (Exception ex) {
            throw ex;
        }
    }

    @Override
    public void delete(Role role) throws DataAccessException {
        try {
            super.getSessionFactory().getCurrentSession().delete(role);
        } catch (Exception ex) {
            throw ex;
        }
    }

    @Override
    public Role getById(Integer roleId) throws DataAccessException {
        Role result = null;
        try {
            result = (Role) super.getSessionFactory().getCurrentSession().get(Role.class, roleId.byteValue());
        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }

    @Override
    public List<Role> getAll() throws DataAccessException {
        List<Role> results = null;
        try {
            Criteria criteria = super.getSessionFactory().getCurrentSession().createCriteria(Role.class);
            criteria.addOrder(Order.asc("roleOrderNumber"));
            results = criteria.setCacheable(true).list();
        } catch (Exception ex) {
            throw ex;
        }
        return results;
    }

    @Override
    public Role getDefaultRole() throws DataAccessException {
        Role result = null;
        try {
            Criteria criteria = super.getSessionFactory().getCurrentSession().createCriteria(Role.class);
            criteria.add(Restrictions.conjunction()
                    .add(Restrictions.eq("roleName", Constants.ROLE_GUEST))
                    .add(Restrictions.eq("roleStatus", Constants.ENABLED)));
            result = (Role) criteria.uniqueResult();
        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }
}
